# coding:utf-8
__author__ = 'peng'

from datetime import datetime, timedelta
import os
import json

from httplib2 import Http
import oauth2client
from oauth2client import client
from oauth2client import tools

from apiclient.discovery import build
from dbobject import *

try:
    import argparse
    flags = argparse.ArgumentParser(parents=[tools.argparser]).parse_args()
except ImportError:
    flags = None

SCOPES = 'https://www.googleapis.com/auth/calendar.readonly'
CLIENT_SECRET_FILE = 'client_secret.json'
APPLICATION_NAME = '日历插入事件'

def get_credentials():

    home_dir = os.path.expanduser('~')
    credential_dir = os.path.join(home_dir, '.credentials')
    if not os.path.exists(credential_dir):
        os.makedirs(credential_dir)
    credential_path = os.path.join(credential_dir,
                                   'calendar-api-quickstart.json')

    store = oauth2client.file.Storage(credential_path)
    credentials = store.get()
    if not credentials or credentials.invalid:
        flow = client.flow_from_clientsecrets(CLIENT_SECRET_FILE, SCOPES)
        flow.user_agent = APPLICATION_NAME
        if flags:
            credentials = tools.run_flow(flow, store, flags)
        else:  # Needed only for compatability with Python 2.6
            credentials = tools.run(flow, store)
        print 'Storing credentials to ' + credential_path
    return credentials

def getCalendarService():
    credentials = get_credentials()
    service = build('calendar', 'v3', http=credentials.authorize(Http()))
    return service


def getContents():

    service = getCalendarService()

    dateStart = datetime.today().date()
    dateEnd = dateStart + timedelta(days=1)

    strStart = str(dateStart) + 'T00:00:00Z'
    strEnd = str(dateEnd) + 'T00:00:00Z'

    eventsResult = service.events().list(
        calendarId='primary',
        timeMin=strStart,
        timeMax=strEnd,
        singleEvents=True,
        orderBy='startTime').execute()
    events = eventsResult.get('items', [])

    resultList = []

    for event in events:
        start = event['start'].get('dateTime', event['start'].get('date'))
        
        resultItem = {}    

        resultItem['date'] = start
        resultItem['summary'] = event['summary']
        resultItem['description'] = event['description'] if event.has_key('description') else ''
        print resultItem['summary']
        resultList.append(resultItem)

    return json.dumps(resultList)

def save_to_jobs(lst):
    lines = json.loads(lst)
    [jobs.save(line) for line in lines]


#本来想着直接允许app客户端直接写入Google日历的，但似乎没啥必要，而且涉及到各种同步更新等等，好麻烦的说

if __name__ == '__main__':
    try:
        save_to_jobs(getContents())
        print("success")
        import sys
        sys.exit(0)
    except Exception:
        print("error")
        sys.exit(1)

    #save_to_calendar()
    #get_credentials2()
    
